package com.pink.filter;

import com.pink.entity.config.AppConfig;
import com.pink.entity.config.Constants;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Order(Constants.ORDER_CORS)
public class CorsFilter extends HttpFilter {

    @Resource
    AppConfig appConfig;

    @Override
    protected void doFilter(HttpServletRequest request,
                            HttpServletResponse response,
                            FilterChain chain) throws IOException, ServletException {
        this.addCorsHeader(request, response);
        chain.doFilter(request, response);
    }

    public void addCorsHeader(HttpServletRequest request,HttpServletResponse response) {
        response.addHeader("Access-Control-Allow-Origin", appConfig.getWebUrl());
        response.addHeader("Access-Control-Allow-Headers","GET, POST, PUT, DELETE, OPTIONS");
        response.addHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, Authorization");
    }
}
